import React, { Dispatch, SetStateAction, useState, useTransition } from 'react'
import { sleep } from 'radash'

interface User {
    id: number,
    username: string
}

const USERS: User[] = [
    {
        id: 1,
        username: '张三',
    },
    {
        id: 2,
        username: '李四',
    },
    {
        id: 3,
        username: '王五',
    },
]

interface ItemProps {
    user: User,
    setUsers: Dispatch<SetStateAction<User[]>>
}

function Item ({ user, setUsers }: ItemProps) {

    const { id, username } = user

    const [ isPending, startTransition ] = useTransition()

    function deleteUser () {
        startTransition(async () => {
            await sleep(1000)
            setUsers(users => users.filter(user => user.id !== id))
        })
    }

    return (
        <li className={ 'flex items-center gap-5' }>
            <span>{ id }</span>
            <span>{ username }</span>
            <button className={ 'p-2 bg-purple-500 disabled:cursor-not-allowed cursor-pointer' }
                    disabled={ isPending }
                    onClick={ deleteUser }>
                delete
            </button>
        </li>
    )
}

export function Todo () {

    const [ users, setUsers ] = useState(USERS)

    return (
        <div className={ 'p-20 bg-slate-300' }>
            <h1 className={ 'text-2xl border-b-2 mb-5' }>Todo</h1>
            <ul className={'space-y-3'}>
                {
                    users.map((user: User) => (
                        <Item key={ user.id } user={ user } setUsers={ setUsers }/>
                    ))
                }
            </ul>
        </div>
    )
}
